SpringApplication 类中含有如下方法:
1 | private boolean deduceWebEnvironment() { |
其中 WEB_ENVIRONMENT_CLASSES 是 SpringApplication 持有的静态属性:1
2private static final String[] WEB_ENVIRONMENT_CLASSES =
new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};
SpringApplication 判断是否是 Web 程序的逻辑非常简单,即判断当前类路径下是否包含 Servlet 和 ConfigurableWebApplicationContext 类:1
2
3
4
5
6
7
8public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
} catch (Throwable var3) {
return false;
}
}
1 | public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { |
以 WEB_ENVIRONMENT_CLASSES 参数来说,ClassUtils.isPresent(className, (ClassLoader)null) 方法将始终返回true,即默认就是 Web 程序